﻿using Daemon.Common;
using Daemon.Common.Helpers;
using Daemon.Infrustructure.EF;
using Daemon.Model;
using Daemon.Repository.Contract;
using Daemon.Repository.EF.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Daemon.Repository.EF
{
	public class TakeAwayUserBookRepository : Repository<TakeAwayUserBook>, ITakeAwayUserBookRepository
	{
		protected override Expression<Func<TakeAwayUserBook, int>> PrimaryKeyExpression => r => r.Id;

		public TakeAwayUserBookRepository(ApiDBContent context) : base(context)
		{
		}

		protected override void UpdateEntitiesBeforeCreate(IEnumerable<TakeAwayUserBook> entities, ApiDBContent context)
		{
			foreach (var entity in entities)
			{
				entity.BookNumber = GenerateOrderNo.Gener("", "YMYY");
			}

			base.UpdateEntitiesBeforeCreate(entities, context);
		}

		protected override IEnumerable<TakeAwayUserBook> IncludeRelationships(IEnumerable<TakeAwayUserBook> entities, ApiDBContent db)
		{
			SetUserInfo(entities);

			SetBoardType(entities);

			SetBookType(entities);

			return entities;
		}

		private void SetBoardType(IEnumerable<TakeAwayUserBook> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayUserBookRelationShipEnum.BoardType))
			{
				return;
			}

			var boardTypeIds = entities.Select(r => r.BoardTypeId).Distinct().ToList();
			var dicBoardType = Context.TakeAwayBoardArea.Where(r => boardTypeIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r);
			foreach (var entity in entities)
			{
				if (dicBoardType.TryGetValue(entity.BoardTypeId, out TakeAwayBoardArea area))
				{
					entity.BoardTypeName = area.Name;
				}
			}
		}

		private void SetBookType(IEnumerable<TakeAwayUserBook> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayUserBookRelationShipEnum.BookType))
			{
				return;
			}

			var booTypeIds = entities.Select(r => r.BookTypeId).ToList();
			var dicBookType = Context.TakeAwayBookType.Where(r => booTypeIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r);
			foreach (var entity in entities)
			{
				if (dicBookType.TryGetValue(entity.BookTypeId, out TakeAwayBookType bookType))
				{
					entity.BookTypeName = bookType.Name;
				}
			}
		}

		private void SetUserInfo(IEnumerable<TakeAwayUserBook> entities)
		{
			if (!RouteParameterHelper.CheckRouteParameter(RelationshipNames, TakeAwayUserBookRelationShipEnum.UserInfo))
			{
				return;
			}

			var userIds = entities.Select(r => r.UserId).ToList();
			var dicUser = Context.TakeAwayUser.Where(r => userIds.Contains(r.Id)).ToDictionary(r => r.Id, r => r);
			foreach (var entity in entities)
			{
				if (dicUser.TryGetValue(entity.UserId, out TakeAwayUser user))
				{
					entity.AddUserName = user.Name;
				}
			}
		}
	}
}
